package pl.edu.pw.MidEmu.UI.Controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;

import pl.edu.pw.MidEmu.Common.Consts;
import pl.edu.pw.MidEmu.Common.Models.ClassSettingsModel;
import pl.edu.pw.MidEmu.Logic.ApplicationService;
import pl.edu.pw.MidEmu.Logic.ProcessHandler;
import pl.edu.pw.MidEmu.UI.Components.ClassLoaderFrame;
import pl.edu.pw.MidEmu.UI.Components.MidasComponent;

/**
 * Controller for loading MIDAS enabled applications
 * @author Mateusz Starodab
 *
 */
public class ClassLoaderController implements ActionListener, DocumentListener
{
	private ClassLoaderFrame _classLoaderFrame;

	private String _orginalFilePath;

	private String _orginalWorkDir;

	private boolean _packageNameChanged = false;

	private ApplicationService appService;

	public ClassLoaderController(ClassLoaderFrame classLoaderFrame)
	{
		_classLoaderFrame = classLoaderFrame;
		appService = new ApplicationService();
	}

	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource().getClass() == JButton.class)
		{
			JButton button = (JButton) e.getSource();
			if (button.getText().equals(Consts.ClassLoader_OKButton))
			{
				if (_classLoaderFrame.isMidasRunning())
				{
					if (_classLoaderFrame.validateApplication())
					{
						String tempWorkDir = _classLoaderFrame.getWorkDir();
						String tempClassName = _classLoaderFrame.getClassName();
						String tempPackage = _classLoaderFrame.getPackageName();
						String tempJVMParameters = _classLoaderFrame.getCommandLineParameters();
						String tempParameters = _classLoaderFrame.getParameters();
						String tempClassPath = _classLoaderFrame.getClassPath();

						ClassSettingsModel model = SaveClassSettings(tempWorkDir, tempClassName, tempPackage, tempJVMParameters, tempParameters, tempClassPath);

						MidasComponent component = _classLoaderFrame.getMidasComponentParent();

						model.set_parameters(model.get_parameters() + " " + Consts.MidasLocalNodeIdCommandLineParameterName + " " + component.getController().getMidas().getNodeName() + " " + Consts.MidasSernsorServerIPAddress + " " + component.getController().getSensorServer().getSensorIP() + " " + Consts.MidasSernsorServerPort + " " + component.getController().getSensorServer().getSensorPort());

						ProcessHandler processHandler = new ProcessHandler(component.getName(), model);
						processHandler.start();

						JOptionPane.showMessageDialog(_classLoaderFrame, String.format(Consts.InformationFrame_ApplicationStarted, new Object[] { _classLoaderFrame.getClassName() }), Consts.InformationFrame_Title, JOptionPane.INFORMATION_MESSAGE);

						_classLoaderFrame.getMidasComponentParent().addRunningApplication(processHandler);
						_classLoaderFrame.getApplicationListParent().rebind();

						_classLoaderFrame.setVisible(false);
						_classLoaderFrame.dispose();
					}
					else
						_classLoaderFrame.reportValidationErrors();
				}
				else
					_classLoaderFrame.reportMidasError();
			}
			else if (button.getText().equals(Consts.ClassLoader_CancelButton))
			{
				_classLoaderFrame.setVisible(false);
				_classLoaderFrame.dispose();
			}
		}
	}

	@Override
	public void changedUpdate(DocumentEvent e)
	{
	}

	public ClassSettingsModel getClassSettingsFromHistory(String path)
	{
		return appService.getModel(path);
	}

	@Override
	public void insertUpdate(DocumentEvent e)
	{
	}

	@Override
	public void removeUpdate(DocumentEvent e)
	{
		if (_classLoaderFrame.getFocusOwner() != null)
		{
			if (_classLoaderFrame.getFocusOwner().getClass() == JTextField.class)
			{
				if (((JTextField) _classLoaderFrame.getFocusOwner()).getName().equals("_tbxWorkDir"))
				{
					if (!_packageNameChanged)
					{
						try
						{
							String tempPackageName = null;
							int length = e.getLength();
							int offset = e.getOffset();

							if (_orginalWorkDir.contains(e.getDocument().getText(0, e.getDocument().getLength())))
							{
								tempPackageName = _orginalWorkDir.substring(offset, offset + length);
								_classLoaderFrame.setPackageName(tempPackageName.replace(File.separatorChar, '.'));
							}
							else
							{
								_packageNameChanged = true;
							}
						}
						catch (BadLocationException ble)
						{
							ble.printStackTrace();
						}
					}
				}
			}
		}
	}

	private ClassSettingsModel SaveClassSettings(String tempWorkDir, String tempClassName, String tempPackage, String tempJVMParameters, String tempParameters, String tempClassPath)
	{
		ClassSettingsModel model = new ClassSettingsModel();
		model.set_workDir(tempWorkDir);
		model.set_className(tempClassName);
		model.set_package(tempPackage);
		model.set_JVMparameters(tempJVMParameters);
		model.set_parameters(tempParameters);
		model.set_path(_orginalFilePath);
		model.set_classPath(tempClassPath);

		appService.addModel(model);

		return model;
	}

	public void setOrginalFilePath(String path)
	{
		_orginalFilePath = path;
	}

	public void setOrginalWorkDir(String orginalWorkDir)
	{
		_orginalWorkDir = orginalWorkDir;
	}

	public void setPackageNameChanged()
	{
		_packageNameChanged = true;
	}
}
